package com.sparrow.manage.template;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.VariablesMap;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.FileTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;

import java.io.*;

public class ThymeleafStaticize {

    private static final Logger logger = LoggerFactory.getLogger(ThymeleafStaticize.class);

    public enum ResolverPath{
        FILE_PATH,
        CLASS_PATH
    }

    private TemplateResolver resolver;

    private TemplateEngine templateEngine;

    public ThymeleafStaticize(String prefix, String suffix, ResolverPath resolverPath) {
        switch (resolverPath){
            case FILE_PATH:
                resolver = new FileTemplateResolver();
                break;
            case CLASS_PATH:
                resolver = new ClassLoaderTemplateResolver();
                break;
            default:
                resolver = new ClassLoaderTemplateResolver();
                break;
        }
        resolver.setPrefix(prefix); //模板所在目录
        resolver.setSuffix(suffix); //模板文件后缀
        resolver.setCacheable(false);
        resolver.setTemplateMode("LEGACYHTML5");
        resolver.setCharacterEncoding("UTF-8");

        this.templateEngine = new TemplateEngine();
        this.templateEngine.setTemplateResolver(resolver);
    }

    /**
     * @param context 模板引擎上下文
     * @param source    模板来源(不可以包含路径)
     * @param fileName  输出文件名(包含路径)
     * @throws IOException
     */
    public void statisticPage(IWebContext context, String source, String fileName) throws IOException {
        try(OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(fileName))), "utf-8")){
            VariablesMap<String, Object> variables = context.getVariables();
            if(variables != null){
                variables.put("source", source);
            }
            this.templateEngine.process(source, context, writer);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
    }
}
